<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #messages {
            border: 1px solid #ccc;
            padding: 10px;
            height: 600px;
            overflow-y: scroll;
            margin-bottom: 10px;
        }
        #messageInput {
            width: 100%;
            height: 60px; /* 增加输入框的高度 */
        }
        #sendButton {
            padding: 10px;
        }
        #wsUrl {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
        }
        #filterCode {
            width: 80%;
            /* padding: 10px;
            margin-bottom: 10px; */
        }
        .editable-input {
            display: none;
            margin: 0;
        }
    </style>
</head>
<body>
    <h1 id="clientName">教师</h1>
    <input type="clientNameInput" class="editable-input" id="input" />
    
    <!-- WebSocket 服务器地址输入框 -->
    <input type="text" id="wsUrl" value="ws://192.168.25.78:8088/ws" placeholder="Enter WebSocket server URL (e.g., wss://yourserver.com/socket)" />
    <button id="connectButton">连接</button>
    <button id="clearMsg">清空消息</button>
    <label>过滤信令：</label>
    <input type="text" id="filterCode" value="229,1002111,1002631" placeholder="输入需要过滤的信令" />

    <div id="messages"></div>
    <textarea id="messageInput" placeholder="Type your message here"></textarea>
    <button id="sendButton">发送</button>

    <script>
        let ws; // WebSocket 对象

        // 定义心跳包内容
        const heartbeatMessage = {"alive":"response"}

        // 定时发送心跳包
        let heartbeatInterval;

        const clientNameLabel = document.getElementById('clientName');
        const clientNameInput = document.getElementById('input');
        clientNameLabel.addEventListener('click', () => {
            clientNameInput.value = clientNameLabel.textContent; // 将标签文本设置为输入框的值
            clientNameLabel.style.display = 'none';      // 隐藏标签
            clientNameInput.style.display = 'inline';    // 显示输入框
            clientNameInput.focus();                     // 聚焦输入框
        });
        // 输入框失去焦点时，保存内容并切换回标签
        clientNameInput.addEventListener('blur', () => {
            clientNameLabel.textContent = clientNameInput.value;  // 更新标签文本
            clientNameLabel.style.display = 'inline';    // 显示标签
            clientNameInput.style.display = 'none';      // 隐藏输入框
        });
        // 按下回车键时，也可以保存内容并切换回标签
        clientNameInput.addEventListener('keydown', (event) => {
            if (event.key === 'Enter') {
                clientNameInput.blur(); // 触发失去焦点事件
            }
        });


        // 连接 WebSocket
        document.getElementById('connectButton').onclick = () => {
            const wsUrl = document.getElementById('wsUrl').value;
            if (ws) {
                ws.close(); // 如果已连接，则先关闭
            }
            ws = new WebSocket(wsUrl);

            // 连接打开时的处理
            ws.onopen = () => {
                addMessage('连接成功');
            };

            // 处理收到的消息
            ws.onmessage = (event) => {
                const response = JSON.parse(event.data);
                if(JSON.stringify(response)=='{"alive":"request"}'){
                    ws.send(JSON.stringify(heartbeatMessage));
                    console.log(JSON.stringify(response))
                    console.log(JSON.stringify(heartbeatMessage))
                }else{
                    debugger
                    let filterCode=document.getElementById('filterCode').value.trim().replace(/，/g, ',').split(',')
                    if(!filterCode.includes(response.m+'')){
                        const formattedDate = getFormatDate()
                        addMessage('<<<<<<<<<<<<接收消息<<<<'+formattedDate +'<<<<<<<<<<<<<<<<<< ');
                        addMessage(JSON.stringify(response));
                        addMessage('');
                        addMessage('');
                        addMessage('');
                    }                  
                }
                
                // addMessage('Received: ' + JSON.stringify(response));
            };

            // 处理连接关闭
            ws.onclose = () => {
                console.log('连接断开');
                addMessage('连接断开');
                // clearInterval(heartbeatInterval); // 清除心跳定时器
            };

            // 处理连接错误
            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
                addMessage('WebSocket error: ' + error.message);
            };
        };

        document.getElementById('clearMsg').onclick = () => {
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML = '';          
        };

        // 发送自定义消息
        document.getElementById('sendButton').onclick = () => {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value;
            if(message.trim()===''){

            }else{
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(message);
                    const formattedDate = getFormatDate()
                    addMessage('');
                    addMessage('');
                    addMessage('>>>>>>>>>>>发送消息>>>>'+ formattedDate+'>>>>>>>>>>>>>>>>>: ');
                    addMessage( message);
                    addMessage('  ' );
                    // messageInput.value = ''; // 清空输入框
                } else {
                    alert('WebSocket is not open. Unable to send message.');
                }
            }
            
        };

        // 添加消息到消息框
        function addMessage(message) {
            const messagesDiv = document.getElementById('messages');
            messagesDiv.innerHTML += message + '<br>';
            messagesDiv.scrollTop = messagesDiv.scrollHeight; // 自动滚动到最底部
        }

        function getFormatDate() {
            const today = new Date();
            const year = today.getFullYear(); // 获取年份
            const month = String(today.getMonth() + 1).padStart(2, '0'); // 获取月份（0-11），并补零
            const day = String(today.getDate()).padStart(2, '0'); // 获取日期，并补零

            const hours = String(today.getHours()).padStart(2, '0'); // 获取小时，并补零
            const minutes = String(today.getMinutes()).padStart(2, '0'); // 获取分钟，并补零
            const seconds = String(today.getSeconds()).padStart(2, '0'); // 获取秒钟，并补零

            const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return formattedDateTime;
        }
    </script>
</body>
</html>